package com.lin.musicplayer;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

/**
 * Created by crystal on 2016/7/6.
 */
public class MusicPlay extends Activity {
    ImageButton prebtn,startbtn,nextbtn,pausebtn,cyclebtn;
    private boolean ispaused=false;
    private MediaPlayer mediaPlayer;
    TextView textView,text;
    private static final File Music_Path=new File("/sdcard/mp3/");
    public List<String> musiclist;
    public int songnum=0;
    public String songname;
    private String data;

    private int status;
    private int p;
    private SeekBar seekBar;
    private MusicHandler musicHandler=new MusicHandler();
    private MusicTread musicTread;
    private boolean autoChange=true,manulChange=false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.musicplay);
       textView= (TextView) findViewById(R.id.songname);
        Intent y=this.getIntent();
       Bundle bundle=this.getIntent().getExtras();
            data=bundle.getString("fileName");
            textView.setText(data);
        mediaPlayer=new MediaPlayer();
        findId();
        play();
        musicTread=new MusicTread();
        musicTread.start();
        listener();
    }
    void play()
    {
        mediaPlayer.reset();
        try {
            String dataSource="/sdcard/mp3/"+data;
            mediaPlayer.setDataSource(dataSource);
            mediaPlayer.prepare();
            mediaPlayer.start();
            text.setText(dataSource);

        }catch (IllegalArgumentException e)
        {
            e.printStackTrace();
        }
        catch (IllegalStateException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                start();
            }
        });
    }
    public MusicPlay()
    {
        musiclist=new ArrayList<String>();
        if(Music_Path.listFiles(new MusicFilter()).length>0)
        {
            for(File file:Music_Path.listFiles(new MusicFilter()))
            {
                musiclist.add(file.getAbsolutePath());
            }
        }
    }
    void findId()
    {
        cyclebtn= (ImageButton) findViewById(R.id.cycle);
        prebtn= (ImageButton) findViewById(R.id.pre);
        startbtn= (ImageButton) findViewById(R.id.start);
        nextbtn= (ImageButton) findViewById(R.id.next);
        pausebtn= (ImageButton) findViewById(R.id.pause);
        text=(TextView)findViewById(R.id.text);
        seekBar= (SeekBar) findViewById(R.id.Bar);

    }
    void listener()
    {
        cyclebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cycle();
            }
        });
        prebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pre();
            }
        });
        startbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                start();
            }

        });

        nextbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                next();
            }
        });
        pausebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try{
                    if(mediaPlayer!=null)
                    {
                        if(ispaused==false)
                        {
                            mediaPlayer.pause();
                            ispaused=true;
                           text.setText("pause");
                        }
                        else if(ispaused==true)
                        {
                            mediaPlayer.start();
                            ispaused=false;
                            text.setText("restart");
                        }
                    }
                }catch (Exception e)
                {
                    e.printStackTrace();
                }

            }
        });
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                try {
                    mediaPlayer.release();
                    text.setText("release");

                }catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                try{
                    mediaPlayer.release();
                    text.setText("error");

                }catch (Exception e)
                {
                    e.printStackTrace();
                }
                return false;
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                textView.setText("当前进度："+progress+"%");
                p=progress;
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(!autoChange&&manulChange)
                {
                   int musicMax=mediaPlayer.getDuration();
                    int seekBaeMarx=seekBar.getMax();
                    seekBar.setProgress(p);
                    status=p*musicMax/seekBaeMarx;
                    mediaPlayer.seekTo(status);
                    mediaPlayer.start();
                    autoChange=true;
                    manulChange=false;
                }
                textView.setText("拖动停止");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                autoChange=false;
                manulChange=true;
             //   mediaPlayer.pause();
                textView.setText("开始拖动");
            }

        });

    }
    public void cycle()
    {
        cyclestart();
    }
    public void cyclestart()
    {
        mediaPlayer.reset();
        try {
            mediaPlayer.reset();
            String dataSource=musiclist.get(songnum);
            setsongname(dataSource);
            mediaPlayer.setDataSource(dataSource);
            mediaPlayer.prepare();
            mediaPlayer.start();
            text.setText("start");

        }catch (IllegalArgumentException e)
        {
            e.printStackTrace();
        }
        catch (IllegalStateException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                cycle();
            }
        });

    }
    public void setsongname(String dataSource)
    {
        File file=new File(dataSource);
        String name=file.getName();
        int index=name.lastIndexOf(".");
        songname=name.substring(0,index);
    }
    public void start()
    {
        mediaPlayer.reset();
        try {
            mediaPlayer.reset();
            String dataSource=musiclist.get(songnum);
            setsongname(dataSource);
            mediaPlayer.setDataSource(dataSource);
            mediaPlayer.prepare();
            mediaPlayer.start();
            text.setText(dataSource);

        }catch (IllegalArgumentException e)
        {
            e.printStackTrace();
        }
        catch (IllegalStateException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                next();
            }
        });
    }
    public void next()
    {
        if(songnum==musiclist.size()-1)
            songnum=0;
        else
            songnum++;
        start();

    }
    public void pre()
    {
        if(songnum==0)
            songnum=musiclist.size()-1;
        else
            songnum=songnum-1;
        start();
    }
    private class MusicHandler extends Handler{

        public void handleMessage(Message msg) {
            if(autoChange)
            {
                try {
                    int position=mediaPlayer.getCurrentPosition();
                    int mMax=mediaPlayer.getDuration();
                    int sMax=seekBar.getMax();
                    status=position*sMax/mMax;
                    seekBar.setProgress(status);
                }catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            else {
                //seekBar.setProgress(0);
     //         textView.setText("finished");
            }

        }

        @Override
        public void close() {

        }

        @Override
        public void flush() {

        }

        @Override
        public void publish(LogRecord logRecord) {

        }
    }
    private   class MusicTread extends Thread{

        @Override
        public void run() {
            while (true)
            {
                try {
                   musicHandler.handleMessage(new Message());
                    Thread.sleep(1000);

                }catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
}
